package com.woniu.user.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.woniu.annotation.RequireRole;
import com.woniu.dto.EmployeeInfoDto;
import com.woniu.dto.IdentityInformationDto;
import com.woniu.dto.StoreOrUserDto;
import com.woniu.exception.user.UserException;
import com.woniu.form.*;
import com.woniu.param.*;
import com.woniu.user.entity.EmployeeInfo;
import com.woniu.user.entity.User;
import com.woniu.user.entity.UserInfo;
import com.woniu.user.mapper.UserRoleMapper;
import com.woniu.user.service.EmployeeInfoService;
import com.woniu.user.service.UserInfoService;
import com.woniu.user.service.UserService;
import com.woniu.user.service.impl.UserInfoServiceImpl;
import com.woniu.utils.JwtUtil;
import com.woniu.utils.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.apache.ibatis.annotations.Param;
import org.hibernate.validator.constraints.Length;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.Map;


/**
 * <p>
 * 登录表 前端控制器
 * </p>
 *
 * @author ly
 * @since 2024年12月05日
 */
@RestController
@RequestMapping("/user")
@Api(tags = "账号信息接口")
public class UserController {
    @Resource
    UserService userService;


    @Resource
    UserRoleMapper userRoleMapper;

    @Resource
    EmployeeInfoService employeeInfoService;


    @Resource
    UserInfoService userInfoService;

    //用户登录（学生，维修员，商家）
    @PostMapping("/loginUser.api")
    @ApiOperation("用户登录（手机号，密码）")
    public Result<IdentityInformationDto> loginUser(@Valid @RequestBody LoginForm loginForm, HttpServletResponse response) throws Exception {
        IdentityInformationDto identityInformationDto = userService.loginFood(BeanUtil.toBean(loginForm, LoginParam.class));
        Map<String, Object> map = BeanUtil.beanToMap(identityInformationDto.getUser());

        //调API生成jwt令牌
        String token = JwtUtil.createToken(map, 600 * 12);
        //通过响应头将jwt响应给客户端
        response.setHeader("token", token);
        response.setHeader("Access-Control-Expose-Headers", "token");

        return Result.getResult(IdentityInformationDto.class).setData(identityInformationDto).setMsg("登录成功");
    }




    //用户名登录（用户）
    @PostMapping("/loginUserByName.api")
    @ApiOperation("用户名登录（用户）")
    public Result<IdentityInformationDto> loginUserByName(@Valid @RequestBody NameLoginForm nameLoginForm, HttpServletResponse response) throws Exception {
        IdentityInformationDto identityInformationDto = userService.loginUserByName(nameLoginForm);
        Map<String, Object> map = BeanUtil.beanToMap(identityInformationDto.getUser());

        //调API生成jwt令牌
        String token = JwtUtil.createToken(map, 600 * 12);
        //通过响应头将jwt响应给客户端
        response.setHeader("token", token);
        response.setHeader("Access-Control-Expose-Headers", "token");

        return Result.getResult(IdentityInformationDto.class).setData(identityInformationDto).setMsg("登录成功");
    }



    //登录验证码获取
    @ApiOperation("登录验证码获取")
    @GetMapping("/sendLoginCode")
    public Result sendLoginCode(@NotNull(message = "手机号不能为空")
                                @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") @RequestParam String phone) throws Exception {
        userService.sendLoginCode(phone);
        return Result.getResult().setMsg("验证码发送成功").setCode(200);
    }

    //验证码登录
    @ApiOperation("验证码登录")
    @GetMapping("/codeLogin")
    public Result codeLogin(@Size(min = 6, max = 6, message = "验证码必须是6位")
                            @Pattern(regexp = "\\d{6}", message = "验证码只能包含数字") @RequestParam String code, @NotNull(message = "手机号不能为空")
                            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") @RequestParam String phone) throws Exception {
        IdentityInformationDto identityInformationDto = userService.codeLogin(code, phone);
        return Result.getResult(IdentityInformationDto.class).setData(identityInformationDto).setMsg("验证码登录成功");
    }





    @PostMapping("/changePassword")
    @ApiOperation("更改密码")
    public Result changePassword(@Valid @RequestBody ChangePassWordForm changePassWordForm, @RequestHeader("token") String token) throws Exception {
        System.out.println(111+changePassWordForm.toString());
        ChangePassWordParam changePassWordParam = BeanUtil.toBean(changePassWordForm, ChangePassWordParam.class);
        Claims claims = JwtUtil.parseToken(token);
        String operator = claims.get("roleId").toString();
        changePassWordParam.setOperator(operator);
        userService.changePassword(changePassWordParam);
        return Result.getResult().setMsg("更改密码成功").setCode(200);
    }

    @GetMapping("/rePassword.api")
    @ApiOperation("根据用户名重置密码")
    @RequireRole("超级管理员")
    @ApiImplicitParam(name = "userName", value = "用户名")
    public Result rePassword(@Length(min = 1, max = 10, message = "用户名长度在1-10位之间")
                                 @NotNull(message = "用户名不能为空") @RequestParam String userName, @RequestHeader("token") String token) throws Exception {
        Claims claims = JwtUtil.parseToken(token);
        String operatorUserName = null;
        try {
            operatorUserName = claims.get("adminName").toString();
            if (userRoleMapper.selectById(Integer.valueOf(claims.get("adminId").toString())).getRoleId() != 5)
                throw new UserException("非超级管理员不得重置用户账号密码", 40013);
        } catch (Exception e) {
            throw new UserException("非管理员不得重置用户账号密码", 40003);
        }
        userService.rePassword(userName, claims.get("adminId").toString());
        return Result.getResult().setMsg("更改密码成功").setCode(200);
    }


    @GetMapping("/selectOneStoreOrUserInfo")
    @ApiOperation("指定账号id查询商家或用户信息")
    @ApiImplicitParam(name = "userId", value = "学生、商户id")
    public Result<UserInfo> selectOneStoreOrUserInfo(@Min(value = 1, message = "账号id必须为正整数") @Max(value = 999, message = "账号id不能超过3位") @RequestParam Integer userId) throws Exception {
        UserInfo userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id", userId));
        return Result.getResult(UserInfo.class).setData(userInfo).setMsg("指定账号id查询商家或用户信息成功").setCode(200);
    }


    @GetMapping("/selectOneEmployeeInfo")
    @ApiOperation("指定账号id查询维修员信息")
    @ApiImplicitParam(name = "userId", value = "维修员id")
    public Result<EmployeeInfoDto> selectOneEmployeeInfo(@Min(value = 1, message = "账号id必须为正整数") @Max(value = 999, message = "账号id不能超过3位")@RequestParam Integer userId) throws Exception {
        EmployeeInfo employeeInfo = employeeInfoService.getOne(new QueryWrapper<EmployeeInfo>().eq("user_id", userId));
        EmployeeInfoDto employeeInfoDto = BeanUtil.toBean(employeeInfo, EmployeeInfoDto.class);
        return Result.getResult(EmployeeInfoDto.class).setData(employeeInfoDto).setMsg("指定账号id查询维修员信息成功").setCode(200);
    }

    @GetMapping("/unableUserByUserId")
    @ApiOperation("通过账号id指定账号禁用")
    @RequireRole("管理员")
    @ApiImplicitParam(name = "userId", value = "学生、商户、维修员id")
    public Result unableUserByUserId(@Min(value = 1, message = "账号id必须为正整数") @Max(value = 999, message = "账号id不能超过3位")@RequestParam Integer userId) throws UserException {
        userService.unableUserByUserId(userId);
        return Result.getResult().setMsg("指定账号id禁用成功").setCode(200);
    }


    @GetMapping("/deleteUserByUserId")
    @ApiOperation("通过账号id指定账号删除")
    @RequireRole("管理员")
    @ApiImplicitParam(name = "userId", value = "学生、商户、维修员id")
    public Result deleteUserByUserId(@Min(value = 1, message = "账号id必须为正整数") @Max(value = 999, message = "账号id不能超过3位")@RequestParam Integer userId) throws UserException {
        userService.deleteUserByUserId(userId);
        return Result.getResult().setMsg("指定用户id删除成功").setCode(200);
    }

    @GetMapping("/ableUserByUserId")
    @ApiOperation("通过账号id指定账号启用")
    @RequireRole("管理员")
    @ApiImplicitParam(name = "userId", value = "学生、商户、维修员id")
    public Result ableUserByUserId(@Min(value = 1, message = "账号id必须为正整数") @Max(value = 999, message = "账号id不能超过3位") @RequestParam Integer userId) throws UserException {
        userService.ableUserByUserId(userId);
        return Result.getResult().setMsg("指定用户id启用成功").setCode(200);
    }



}

